package com.example.shopping.controller;

import com.example.shopping.common.consts.MessageEnum;
import com.example.shopping.common.consts.ResultEnum;
import com.example.shopping.common.response.RestResponse;
import com.example.shopping.pojo.domain.UserBean;
import com.example.shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Dream
 * @version 1.0
 * @date 2020/11/9 18:44
 */
@RestController
@RequestMapping(value="user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param xh
     * @param password
     * @return
     */
    @RequestMapping(value="/login")
    public RestResponse login(@RequestParam(value="xh") String xh,
                              @RequestParam(value="password") String password,
                              HttpServletRequest request){
        return new RestResponse(ResultEnum.SUCCESS,userService.getUser(xh,password,request));
    }

    @RequestMapping(value="/loginCheck")
    public RestResponse loginCheck( HttpServletRequest request){
        UserBean userBean=(UserBean) request.getSession().getAttribute("user");
        if(userBean==null){
            return new RestResponse(ResultEnum.SUCCESS, MessageEnum.NO_LOGIN);
        }else{
            return new RestResponse(ResultEnum.SUCCESS,userBean);
        }
    }

    /**
     * 添加新用户
     * @param userBean
     * @return
     */
    @RequestMapping(value="/add")
    public RestResponse addUser(@Validated @RequestBody UserBean userBean){
        return new RestResponse(ResultEnum.SUCCESS,userService.addUser(userBean));
    }

    /**
     * 修改密码
     * @param xh
     * @param password
     * @return
     */
    @RequestMapping(value="/upadtePswd")
    public RestResponse upadtePswd(@RequestParam(value="xh") String xh,
                                   @RequestParam(value="password") String password){
        return new RestResponse(ResultEnum.SUCCESS,userService.updatePswd(password,xh));
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value="/exit")
    public RestResponse exit(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return new RestResponse(ResultEnum.SUCCESS,MessageEnum.USER_EXIT);
    }
}
